package cn.it.shop.service.listener;
import javax.servlet.http.HttpSessionAttributeListener;
import javax.servlet.http.HttpSessionBindingEvent;

import org.springframework.security.core.context.SecurityContext;

import cn.it.shop.pojo.Account;

public class AccountSessionAttributeListener implements
		HttpSessionAttributeListener {

	@Override
	public void attributeAdded(HttpSessionBindingEvent event) {
		// 如果登陆的信息存储到session中
		if(event.getName().equals("SPRING_SECURITY_CONTEXT")){
			System.out.println("---attributeAdded---");
			SecurityContext context=(SecurityContext) event.getSession().getAttribute("SPRING_SECURITY_CONTEXT");
			Account account = (Account)context.getAuthentication().getPrincipal();
			event.getSession().setAttribute("account", account);
		}

	}

	@Override
	public void attributeRemoved(HttpSessionBindingEvent event) {
		if(event.getName().equals("SPRING_SECURITY_CONTEXT")){
			System.out.println("-----attributeRemoved-----");
			event.getSession().removeAttribute("account");
		}
	}

	@Override  // 当值替换的时候执行操作
	public void attributeReplaced(HttpSessionBindingEvent event) {
		if(event.getName().equals("SPRING_SECURITY_CONTEXT")){
			System.out.println("---attributeReplaced---");
			SecurityContext context=(SecurityContext) event.getSession().getAttribute("SPRING_SECURITY_CONTEXT");
			Account account = (Account)context.getAuthentication().getPrincipal();
			event.getSession().setAttribute("account", account);
		}
	}

}
